using System;
using System.Collections.Generic;
using System.Text;

using Microsoft.Win32;

namespace CodeComment.NET
{
    internal static class SettingsHandler
    {
        #region Constants
        private const string ConfigSubKeyFullPath = "Software\\CodeCommentNet\\Config";
        private const string LastUsedCommentsFilenamePathKeyName = "LastUsedCommentsFilenamePath";
        #endregion

        /// <summary>
        /// This method will try to get a full path to comments output
        /// file. It will try to get the path from a predefined Registry key.
        /// </summary>
        /// <returns>Returns found path or an emptry string if registry key
        /// can not be found or if an error happens while trying to get the 
        /// path.</returns>
        public static string GetCommentsOutputFilenamePath()
        {
            string retVal = String.Empty;

            try
            {
                RegistryKey currentUserRegKey = RegistryKey.OpenRemoteBaseKey(Microsoft.Win32.RegistryHive.CurrentUser, "");
                RegistryKey subKey;

                string subKeyName = SettingsHandler.ConfigSubKeyFullPath;
                subKey = currentUserRegKey.OpenSubKey(subKeyName);

                if (subKey != null)
                {
                    string filePath = subKey.GetValue(SettingsHandler.LastUsedCommentsFilenamePathKeyName) as string;
                    if (!String.IsNullOrEmpty(filePath))
                    {
                        retVal = filePath;
                    }
                }
            }
            catch (Exception)
            {
            }

            return retVal;
        }

        /// <summary>
        /// This  method will store <paramref name="filenamePath"/> into registry.
        /// </summary>
        /// <param name="filenamePath">A filename with full path to last used
        /// comments output file.</param>
        public static void StoreCommentsOutputFilenamePath(string filenamePath)
        {
            SettingsHandler.StoreConfigParameter(SettingsHandler.LastUsedCommentsFilenamePathKeyName, filenamePath);
        }

        private static void StoreConfigParameter(string paramName, string paramValue)
        {
            try
            {
                RegistryKey currentUserRegKey = RegistryKey.OpenRemoteBaseKey(Microsoft.Win32.RegistryHive.CurrentUser, "");
                RegistryKey subKey;

                string subKeyName = SettingsHandler.ConfigSubKeyFullPath;
                subKey = currentUserRegKey.OpenSubKey(subKeyName, true);

                if (subKey == null)
                {
                    subKey = currentUserRegKey.CreateSubKey(subKeyName);
                }
                subKey.SetValue(paramName, paramValue);
            }
            catch (Exception)
            {
            }
        }
    }
}
